package com.lonely.deliver.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lonely.common.utils.SecurityUtils;
import com.lonely.deliver.domain.entity.SysOrderDeliver;
import com.lonely.deliver.domain.entity.SysOrderDeliverSynchronizedTask;
import com.lonely.deliver.enums.OrderDeliverSynchronizedTaskEnum;
import com.lonely.deliver.mapper.SysOrderDeliverSynchronizedTaskMapper;
import com.lonely.deliver.service.IOrderDeliverService;
import com.lonely.deliver.service.IOrderDeliverSynchronizedTaskService;
import com.lonely.order.domain.entity.SysOrder;
import com.lonely.order.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : 黄志标
 * @date: 2025/10/17 10:41
 * @description: 订单发货单同步任务服务实现类
 */
@Service
public class OrderDeliverSynchronizedTaskServiceImpl extends ServiceImpl<SysOrderDeliverSynchronizedTaskMapper, SysOrderDeliverSynchronizedTask> implements IOrderDeliverSynchronizedTaskService {

    @Autowired
    private IOrderDeliverService orderDeliverService;

    @Autowired
    private IOrderService orderService;

    /**
     * 添加订单发货单同步任务
     *
     * @param orders
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOrderDeliverSynchronizedTask(List<SysOrder> orders) {

        if (CollUtil.isEmpty(orders)) {
            return;
        }

        List<SysOrderDeliverSynchronizedTask> synchronizedTasks = new ArrayList<>();
        for (SysOrder order : orders) {
            SysOrderDeliverSynchronizedTask synchronizedTask = new SysOrderDeliverSynchronizedTask();
            synchronizedTask.setOrderId(order.getId());
            synchronizedTask.setProduceOrderId(Convert.toStr(order.getProduceOrderId()));
            synchronizedTask.setLastSyncTime(null);
            synchronizedTask.setStatus(OrderDeliverSynchronizedTaskEnum.StatusEnum.NOT_SYNCHRONIZED.getStatus());
            synchronizedTask.setCreateBy(SecurityUtils.getUserId());
            synchronizedTask.setUpdateBy(SecurityUtils.getUserId());
            synchronizedTasks.add(synchronizedTask);
        }
        super.saveBatch(synchronizedTasks);
    }

    /**
     * 执行订单发货单同步任务
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doingSynchronizedTask() {
        List<SysOrderDeliverSynchronizedTask> synchronizedTasks = super.list(new LambdaQueryWrapper<SysOrderDeliverSynchronizedTask>()
                .eq(SysOrderDeliverSynchronizedTask::getStatus, OrderDeliverSynchronizedTaskEnum.StatusEnum.NOT_SYNCHRONIZED.getStatus())
        );
        if (CollUtil.isEmpty(synchronizedTasks)) {
            log.debug("没有待同步的订单发货单任务...");
            return;
        }

        List<Long> orderIds = synchronizedTasks.stream().map(SysOrderDeliverSynchronizedTask::getOrderId).distinct().collect(Collectors.toList());
        List<SysOrder> sysOrders = this.orderService.listByIds(orderIds);
        this.orderDeliverService.synchronizerOrderDeliver(sysOrders, false);

        // 更新任务状态
        List<Long> synchronizedSuccessOrderIds = this.orderDeliverService.list(new LambdaQueryWrapper<SysOrderDeliver>()
                .in(SysOrderDeliver::getOrderId, orderIds)
        ).stream().map(SysOrderDeliver::getOrderId).distinct().collect(Collectors.toList());

        // 同步失败的订单id集合
        List<Long> synchronizedErrorOrderIds = CollUtil.subtractToList(orderIds, synchronizedSuccessOrderIds);

        if (CollUtil.isNotEmpty(synchronizedSuccessOrderIds)) {
            super.update(new LambdaUpdateWrapper<SysOrderDeliverSynchronizedTask>()
                    .in(SysOrderDeliverSynchronizedTask::getOrderId, synchronizedSuccessOrderIds)
                    .set(SysOrderDeliverSynchronizedTask::getLastSyncTime, new Date())
                    .set(SysOrderDeliverSynchronizedTask::getStatus, OrderDeliverSynchronizedTaskEnum.StatusEnum.SYNCHRONIZED.getStatus())
                    .set(SysOrderDeliverSynchronizedTask::getRemark, "定时任务同步成功")
            );
        }

        if (CollUtil.isNotEmpty(synchronizedErrorOrderIds)) {
            super.update(new LambdaUpdateWrapper<SysOrderDeliverSynchronizedTask>()
                    .in(SysOrderDeliverSynchronizedTask::getOrderId, synchronizedErrorOrderIds)
                    .set(SysOrderDeliverSynchronizedTask::getLastSyncTime, new Date())
            );
        }

    }
}
